// pages/shoppingcar/shoppingcar.js
var app = getApp();
var GlobalData = require('../../utils/GlobalData.js');
var dataManager = require('../../utils/dataManager.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    config: {
      show: "meng"
    },

    shopcar: [],
    allSelImg: false,
    isDel: false,
    isRevise: false,
    productDetails: {},
    payType: 0,
    selArr: [true, false, false],
    payTypeArr: [],
    shopcarType: {},
    buyInfo: [],
    price: { "bonuspoints": 0, "cash": 0 },
    isAdd: false,
    productDetailprice: { bonuspoints: 0, cash: 0 },
    showTabar: false,
    heigth: 93.4

  },
  tapopen: function () {
    this.setData({
      config: {
        show: "meng1"
      }
    })
  },
  taphide: function () {
    this.setData({
      config: {
        show: "meng"
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getShopCar();
    //   app.onshowModal("添加购物车成功")
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      showTabar: app.getConfig().isFormal
    })
    this.getShopCar();
  },
  getShopCar() {
    dataManager.rigisterObserver("getshoppingcart", this.onCompleteGetShoppingCar, this);
    dataManager.getShoppingCar();
  },
  /**获取购物车回调函数 */
  onCompleteGetShoppingCar() {
    let title = "购物车"
    if (GlobalData.shopcarIntegral.length) {
      title = "购物车(" + GlobalData.shopcarIntegral.length + ")";
    }
    // let arrbuy = [];
    wx.setNavigationBarTitle({
      title: title,
      success: function (res) {
        // success
      }
    })
    this.data.shopcar = GlobalData.clone(GlobalData.shopcarIntegral);
    let arrbuy = GlobalData.clone(this.data.buyInfo);
    this.data.buyInfo = [];
    for (let i = 0; i < this.data.shopcar.length; i++) {

      if (arrbuy.length) {
        for (let j = 0; j < arrbuy.length; j++) {
          if (this.data.shopcar[i].id == arrbuy[j].id) {
            this.data.shopcar[i]["sel"] = true;
            this.data.buyInfo.push(this.data.shopcar[i]);
          }
        }
      } else {
        this.data.shopcar[i]["sel"] = false;
      }
      if (this.data.shopcar[i].num > this.data.shopcar[i].stock) {
        this.data.shopcar[i]["enough"] = false;
      } else {
        this.data.shopcar[i]["enough"] = true;
      }
      for (let j = 0; j < this.data.shopcar[i].imgpath.length; j++) {
        if (this.data.shopcar[i].imgpath[j].sortno == 3) {
          this.data.shopcar[i]['img'] = this.data.shopcar[i].imgpath[j].path;
        }
      }
    }
    if (!this.data.shopcar.length) {
      this.data.buyInfo = [];
      this.data.allSelImg = false;
    }
    if (this.data.shopcar.length && this.data.shopcar.length == this.data.buyInfo.length) {
      this.data.allSelImg = true;
    }
    this.setData({
      shopcar: this.data.shopcar,
      buyInfo: this.data.buyInfo,
      allSelImg: this.data.allSelImg
    });
    this.getPriceSum();
  },
  //二分查找法
  BinarySearch(arr, id) {
    let l = 0;
    let r = arr.length - 1;
    while (l <= r) {
      let num = (r - l) / 2
      let mid = l + parseInt(num.toString());
      if (arr[mid].id == id) return true;
      if (arr[mid].id > id) r = mid - 1;
      else
        l = mid + 1;
    }
    return false;
  },
  /**选中某个商品 */
  onSelProduct(e) {
    let data = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    this.data.shopcar[index]["sel"] = !this.data.shopcar[index]["sel"];
    let count = 0;
    let obj = {};
    /**取消选中 */
    if (this.data.buyInfo.length) {
      for (let j = 0; j < this.data.buyInfo.length; j++) {
        if (this.data.shopcar[index]["sel"]) {
          if (this.data.shopcar[index]["id"] != this.data.buyInfo[j]["id"]) {
            this.data.buyInfo.push(data);
            break;
          }
        } else {
          if (this.data.shopcar[index]["id"] == this.data.buyInfo[j]["id"]) {
            this.data.buyInfo.splice(j, 1);
            break;
          }
        }
      }
    } else {
      this.data.buyInfo.push(data);
    }
    /**选中 */
    for (let i = 0; i < this.data.shopcar.length; i++) {
      if (this.data.shopcar[i]["sel"]) {
        count += 1;
      }
    }
    if (count == this.data.shopcar.length) {
      this.data.allSelImg = true;
    } else {
      this.data.allSelImg = false;
    }
    this.setData({
      shopcar: this.data.shopcar,
      buyInfo: this.data.buyInfo,
      allSelImg: this.data.allSelImg

    })
    /**计算总的积分和价格 */
    this.getPriceSum();
  },
  onAllSel() {
    if (!this.data.shopcar.length) {
      this.setData({
        allSelImg: false
      })
      return;
    }
    this.data.allSelImg = !this.data.allSelImg;
    for (let i = 0; i < this.data.shopcar.length; i++) {
      if (this.data.allSelImg)
        this.data.shopcar[i]["sel"] = true;
      else
        this.data.shopcar[i]["sel"] = false;
    }
    if (this.data.allSelImg) {
      this.data.buyInfo = GlobalData.clone(this.data.shopcar);
    } else {
      this.data.buyInfo = [];
    }
    this.setData({
      shopcar: this.data.shopcar,
      buyInfo: this.data.buyInfo,
      allSelImg: this.data.allSelImg

    })
    /**计算总的积分和价格 */
    this.getPriceSum();
  },
  /**计算商品的总积分和总价钱 */
  getPriceSum() {
    let bonuspoints = 0;
    let cash = 0;
    for (let i = 0; i < this.data.buyInfo.length; i++) {
      bonuspoints += parseFloat(this.data.buyInfo[i]["bonuspoints"]) * parseFloat(this.data.buyInfo[i].num);
      cash += parseFloat(this.data.buyInfo[i]["cash"]) * parseFloat(this.data.buyInfo[i].num);
    }
    this.setData({
      ['price.bonuspoints']: bonuspoints,
      ['price.cash']: cash,
    })
  },

  /**改变购物车信息 1：减 2:加 3：清空某一种商品 */
  onChangeInfo(e) {
    // data, type
    let data = e.currentTarget.dataset.item;
    let type = parseInt(e.currentTarget.dataset.type);
    switch (type) {
      // 减
      case 1:
        // if()
        // this.isAdd = false;
        if ((data.num - 1) == 0) {
          for (let i = 0; i < this.data.buyInfo.length; i++) {
            if (this.data.buyInfo[i].id == data.id) {
              this.data.buyInfo.splice(i, 1)
            }
          }
        }
        this.setData({
          isAdd: false,
          buyInfo: this.data.buyInfo
        })
        data.num = (data.num - 1) > 0 ? (data.num - 1) : 0;
        this.onExchangeData(data, type)
        break;
      // 加
      case 2:
        if (data.num >= data.stock) {
          app.onshowModal("库存不足。");
          return;
        }
        this.setData({
          isAdd: false,
        })
        // this.isAdd = false;
        data.num = data.num + 1;
        this.onExchangeData(data, type)
        break;
      //删除
      case 3:

        // this.isAdd = false;
        data.num = 0;
        for (let i = 0; i < this.data.buyInfo.length; i++) {
          if (this.data.buyInfo[i].id == data.id) {
            this.data.buyInfo.splice(i, 1)
          }
        }
        this.setData({
          isAdd: false,
          buyInfo: this.data.buyInfo
        })
        this.onExchangeData(data, type)
        break;
      //修改支付方式
      case 4:
        this.setData({
          isAdd: true,
          shopcarType: data
        })
        dataManager.rigisterObserver("getgoodsdetails", this.getGoodsDetails, this);
        dataManager.getProductDetails(data.goodsid);
        break;
    }
  },
  /**获取商品详情的回调函数 */
  getGoodsDetails() {
    this.data.payTypeArr = [];
    this.data.productDetails = GlobalData.productDetails;
    this.data.productDetailprice = this.data.productDetails.exchanges[0]
    for (let j = 0; j < this.data.productDetails.imgs.length; j++) {
      if (this.data.productDetails.imgs[j].sortno == 2) {
        this.data.productDetails['img'] = this.data.productDetails.imgs[j].path;
      }
    }
    for (let i = 0; i < this.data.productDetails.exchanges.length; i++) {
      if (this.data.productDetails.exchanges[i].cash == 0 && this.data.productDetails.exchanges[i].bonuspoints == 0)
        break;
      else
        this.data.payTypeArr.push(this.data.productDetails.exchanges[i])
    }
    this.data.isRevise = !this.data.isRevise;
    this.setData({
      productDetails: this.data.productDetails,
      productDetailprice: this.data.productDetailprice,
      payTypeArr: this.data.payTypeArr,
      isRevise: this.data.isRevise,
      config: {
        show: "meng1"
      }

    })
  },
  /**修改购物车 */
  onExchangeData(data, type) {
    let obj = {};
    obj["id"] = data.id;
    obj["goodsid"] = data.goodsid;
    obj["bonuspoints"] = data.bonuspoints;
    obj["cash"] = data.cash;
    obj["num"] = data.num;
    dataManager.rigisterObserver("updateshoppingcart", this.onCompleteAddCar, this);
    dataManager.onAddCar(obj);
  },
  /**修改购物车成功 */
  onCompleteAddCar() {
    var that = this;
    if (this.data.isAdd) {
      wx.showModal({
        title: '提示',
        content: "修改成功",
        showCancel: false,
        success: function (res) {
          that.setData({
            config: {
              show: "meng"
            }
          })
        }
      })
    }
    that.getShopCar();
  },
  /**选择支付方式 */
  onPayType(e) {
    let type = parseInt(e.currentTarget.dataset.type)
    this.data.payType = type;
    // this.isSelPayType = !this.isSelPayType;
    for (let i = 0; i < 3; i++) {
      if (this.data.payType == i) {
        this.data.selArr[i] = true;
      } else
        this.data.selArr[i] = false;
    }
    // this.data.selArr[this.data.payType] = false;
    this.data.productDetailprice["bonuspoints"] = this.data.payTypeArr[this.data.payType].bonuspoints;
    this.data.productDetailprice["cash"] = this.data.payTypeArr[this.data.payType].cash;
    this.setData({
      payType: this.data.payType,
      selArr: this.data.selArr,
      productDetailprice: this.data.productDetailprice
    });
  },
  /**加入购物车 */
  onJoincar() {
    let obj = {};
    obj["id"] = this.data.shopcarType.id;
    obj["goodsid"] = this.data.shopcarType.goodsid;
    obj["bonuspoints"] = this.data.payTypeArr[this.data.payType].bonuspoints;
    obj["cash"] = this.data.payTypeArr[this.data.payType].cash;
    obj["num"] = this.data.shopcarType.num;
    dataManager.rigisterObserver("updateshoppingcart", this.onCompleteAddCar, this);
    dataManager.onAddCar(obj);
  },
  /**关闭详情显示 */
  onClose() {
    this.setData({
      isRevise: false,
      config: {
        show: "meng"
      }
    })
  },
  /**立即兑换 */
  onConfirmeExchange() {
    if (!this.data.buyInfo.length) {
      app.onshowModal("请选择兑换的商品。")
      return;
    }
    var arrT = GlobalData.clone(this.data.buyInfo)
    var temp = [];
    let num = 0;
    let str = ""
    for (let i = 0; i < this.data.buyInfo.length; i++) {
      num = 0;
      for (let j = 0; j < arrT.length;) {
        if (this.data.buyInfo[i].goodsid == arrT[j].goodsid) {
          num += arrT[j].num
          arrT.splice(j, 1);
        } else {
          j++
        }
      }
      if (num > this.data.buyInfo[i].stock) {
        str += this.data.buyInfo[i].goodsname + ',';
      }
    }
    if (str) {
      app.onshowModal(str + "库存不足。");
      return;
    }
    if (GlobalData.homeData) {
      if (this.data.price["bonuspoints"] > parseInt(GlobalData.homeData.bonuspoints)) {
        app.onshowModal("积分不足，请更换兑换方式。")
        return;
      }
      GlobalData.isdirectbuy = false;
      GlobalData.buyInfo = GlobalData.clone(this.data.buyInfo);
      GlobalData.price = GlobalData.clone(this.data.price);
      dataManager.UseNavigateTo("/pages/integralconfirm/integralconfirm", false);
    }
  },


  goHome: function (event) {
    let index = parseInt(event.currentTarget.dataset.id)
    switch (index) {
      case 1:
      dataManager.UseNavigateTo("/pages/integralmall/integralmall",true);
        break;
      case 3:
       dataManager.UseNavigateTo("/pages/myintegral/myintegral",true);
        break;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})